<?php

declare(strict_types=1);

namespace app\shop\controller;

// use think\api\Client;
use \Firebase\JWT\JWT;
use think\Exception;
use think\facade\Request;
use app\BaseController;

class Base extends BaseController
{
    public function __construct()
    {
        $this->initialize();
    }
    protected function initialize()
    {
        header('Access-Control-Allow-Origin:http://localhost:8080');
    }

    /**
     * @name 生成token
     */
    protected function signToken($id, $mobile)
    {
        $key = '1164601554@qq.com'; //key
        $time = time(); //当前时间
        $token = [
            'iss' => $_SERVER['SERVER_NAME'], //签发者 可选
            'aud' => 'http://localhost:8080', //接收该JWT的一方，可选
            'iat' => $time, //签发时间
            'nbf' => $time, //(Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp' => $time + 7200, //过期时间,这里设置2个小时
            'data' => '{"id":' . $id . ',"mobile":' . $mobile . '}'
        ];
        return JWT::encode($token, $key); //输出Token
    }

    /**
     * @name  验证token
     */
    protected function checkToken($jwt)
    {
        $key = '1164601554@qq.com'; //key要和签发的时候一样
        try {
            JWT::$leeway = 60; //当前时间减去60，把时间留点余地
            $decoded = JWT::decode($jwt, $key, ['HS256']); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            return ['code' => 0, 'data' => $arr];
        } catch (\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
            return ['code' => 2, 'msg' => $e->getMessage()];
        } catch (\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
            return ['code' => 2, 'msg' => $e->getMessage()];
        } catch (\Firebase\JWT\ExpiredException $e) {  // token过期
            return ['code' => 2, 'msg' => $e->getMessage()];
        } catch (Exception $e) {  //其他错误
            return ['code' => 2, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @name  登录验证
     */
    public function login()
    {
        if (request()->isPost()) {
            $token = Request::param('token');
            $res = $this->checkToken($token);
            if ($res['code'] == 0) {
                return json(['code' => 0]);
            } else {
                return json(['code' => 2]);
            }
        }
    }
}
